# 查找并统计最近更新的文章
# 主要依靠update标签
import os
import re
import time
from datetime import datetime

def scan_all_md_files(yml_path):
    path_pre = '/Users/rustfisher/Desktop/ws/wiki-ws/mk-android-wiki-proj/mk-an-wiki/docs/'
    pattern = re.compile(r': (.*?).md', re.S)
    filepath_list = []  # md files 
    with open(yml_path) as yml:
        for line in yml.readlines():
            line = str(line)

            cur_urls = re.findall(pattern, line)
            if len(cur_urls) > 0:
                if cur_urls[0] == '/':
                    continue
                if cur_urls[0] == 'tech-note-index':
                    continue
                filepath_list.append(path_pre + cur_urls[0] + '.md')

    print('markdown文件个数: ', len(filepath_list))

    err_filepath_list = []
    md_and_time_list = []
    for md_file in filepath_list:
        if not os.path.exists(md_file):
            err_filepath_list.append(md_file)
            continue
        updated_time = '' # 更新时间
        title = ""
        desc = ""
        timestamp = 0
        with open(md_file) as md:
            for line in md.readlines():
                line = str(line)
                if line.startswith("updated_time: "):
                    updated_time = line.split(" ")[-1].strip() # 取出最后的时间
                    updated_time = updated_time.split("+")[0]
                    dt_time = datetime.strptime(updated_time, '%Y-%m-%dT%H:%M:%S')
                    timestamp = dt_time.timestamp()
                    updated_time = updated_time.split("T")[0]
                    # print(str(dt_time.timestamp()))
                    continue
                if line.startswith("title: "):
                    title = line.split("title: ")[-1].strip()
                    continue
                if line.startswith("description: "):
                    desc = line.split(" ")[-1].strip()
                    continue

        if not updated_time == '':
            md_and_time_list.append((timestamp, updated_time, title, md_file, desc))
    
    md_and_time_list.sort(key=lambda x:(-x[0])) # 目前只有数字能排序

    # for i in range(0,10):
    #     print(md_and_time_list[i])

    write_recent_post(md_and_time_list)


def write_recent_post(input_list):
    print("开始写最近更新")
    recent_post_file = "/Users/rustfisher/Desktop/ws/wiki-ws/mk-android-wiki-proj/mk-an-wiki/docs/recent-post.md"
    if os.path.exists(recent_post_file):
        os.remove(recent_post_file)

    with open(recent_post_file, 'w') as s:
        s.write("---\n")
        s.write("title: 最近更新|铁手渔夫\n")
        s.write("keywords: 安卓,教程,java,Android教程\n")
        s.write("description: Android教程，最近更新的文章。an.rustfisher.com\n")
        s.write("updated_time: 2022-02-03T00:43:57+08:00\n")
        s.write("---\n\n")
        
        cur_i = 0
        for data in input_list:
            if cur_i < 11:
                title = data[2]
                url = data[3].split("docs")[-1].split(".")[0]
                s.write("!!! note \"\"\n\n")
                s.write("    <b>" + title + '</b>\n\n')
                s.write('    更新日期: ' + data[1] + '\n\n')
                s.write("    [开始阅读"  + "](" + url + "/){.md-button}\n\n")

            cur_i += 1


if __name__ == '__main__':
    print('--- 开始寻找更新时间 --- ')
    scan_all_md_files('/Users/rustfisher/Desktop/ws/wiki-ws/mk-android-wiki-proj/mk-an-wiki/mkdocs.yml')
    print('--- END --- ')
